﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DiskInspector.Model;

namespace DiskInspector
{
    public partial class MainBootRecordForm : Form
    {
        private readonly MainBootRecord MBR;

        private byte[] buffer;

        public MainBootRecordForm(Form owner, MainBootRecord MBR)
        {
            this.Owner = owner;
            this.MBR = MBR;
            InitializeComponent();
        }

        private void MainBootRecordForm_Load(object sender, EventArgs e)
        {
            tb_MasterBootstrapLoaderCode.Text = MBR.MasterBootstrapLoaderCode.ToByteString();
            tb_WindowsDiskSignature.Text = MBR.WindowsDiskSignature.ToByteString();
            tb_Signature.Text = MBR.Signature.ToByteString();

            tb_DiskPartitionTableIndex.Items.AddRange(MBR.DiskPartitionTables
                .Where(d => d.SectorsPrecedingPartition != 0)
                .Select((d, index) => index + 1)
                .Cast<object>()
                .ToArray());
        }

        private void tb_DiskPartitionTableIndex_SelectedIndexChanged(object sender, EventArgs e)
        {
            var DPT = MBR.DiskPartitionTables[int.Parse(tb_DiskPartitionTableIndex.SelectedItem.ToString()) - 1];

            tb_BootIndicator.Text = DPT.BootIndicator.ToByteString();
            tb_StartHead.Text = DPT.StartHead.ToString();
            tb_StartSector.Text = DPT.StartSector.ToString();
            tb_StartCylinder.Text = DPT.StartCylinder.ToString();
            tb_PartitionTypeIndicator.Text = DPT.PartitionTypeIndicator.ToByteString();
            tb_EndHead.Text = DPT.EndHead.ToString();
            tb_EndSector.Text = DPT.EndSector.ToString();
            tb_EndCylinder.Text = DPT.EndCylinder.ToString();
            tb_SectorsPrecedingPartition.Text = DPT.SectorsPrecedingPartition.ToString();
            tb_SectorsInPartition.Text = DPT.SectorsInPartition.ToString();

            btn_DBR.Enabled = DPT.SectorsPrecedingPartition != 0;
        }

        private void btn_Enter_Click(object sender, EventArgs e)
        {
            var DPT = MBR.DiskPartitionTables[int.Parse(tb_DiskPartitionTableIndex.SelectedItem.ToString()) - 1];

            using (var disk = DiskManager.GetStream()) 
            {
                long offset = Math.BigMul(DPT.SectorsPrecedingPartition, DiskManager.SectorSize);
                buffer = DiskManager.ReadSector(disk, offset);
            }

            var DBR = DataParser.Parse<DOSBootRecord>(buffer);
            var form = new DOSBootRecordForm(this, DPT, DBR);
            form.ShowDialog();
        }
    }
}
